package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.config.WxV3PayConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.wx.HttpClientSslUtils;
import com.ruoyi.common.utils.wx.WeChatUtil;
import com.ruoyi.system.domain.fx.FxUser;
import com.ruoyi.system.domain.vo.WxLoginVo;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.fx.FxUserMapper;
import com.ruoyi.system.service.fx.IFxToJoinService;
import com.ruoyi.system.service.fx.IFxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private FxUserMapper fxUserMapper;
    @Autowired
    private IFxUserService fxUserService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IFxToJoinService fxToJoinService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, Long roleId)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        whether(loginUser, roleId); // 校验是否可以登录
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }


    // 微信登录
    @Transactional
    public AjaxResult loginOpenid(WxLoginVo wxLoginVo) {
        try {
            AjaxResult ajax = AjaxResult.success();
            // 微信小程序ID
            String appid = WxV3PayConfig.APP_ID;
            // 微信小程序秘钥
            String secret = WxV3PayConfig.secret;

            // 根据小程序穿过来的code想这个url发送请求
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                    + "&secret=" + secret
                    + "&js_code=" + wxLoginVo.getCode()
                    + "&grant_type=authorization_code";
            // 发送请求，返回Json字符串
            String str = WeChatUtil.httpRequest(url, "GET", null);
            // 转成Json对象 获取openid
            JSONObject jsonObject = JSONObject.parseObject(str);
            // 我们需要的openid，在一个小程序中，openid是唯一的
            String openid = jsonObject.get("openid").toString();
            String sessionKey = jsonObject.get("session_key").toString();

            String access_token = jsonObject.getString("access_token");
//            String refresh_token = jsonObject.getString("refresh_token");
            // 拉取用户信息(需scope为 snsapi_userinfo)
//            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
//                    + "&openid=" + openid
//                    + "&lang=zh_CN";
//            String InfoStr = WeChatUtil.httpRequest(infoUrl, "GET", null);
//            JSONObject userInfo = JSONObject.parseObject(InfoStr);

            wxLoginVo.setSessionKey(sessionKey);
            SysUser sysUser = new SysUser();
            if (StringUtils.isNotEmpty(openid)){
                String phoneNumber = this.getPhoneNumber(wxLoginVo);
                //先用电话号码判断有无此用户
//                FxUser  fxUser=new FxUser();
//                fxUser.setPhoneNumber(phoneNumber);
//                List<FxUser> bausers = fxUserMapper.selectFxUserList(fxUser);
//                if(bausers.size()!=0){
//                    fxUser=bausers.get(0);
//                }
                FxUser fxUser = fxUserMapper.selectFxUserByPhone(phoneNumber);
                //用户不存在
                String password = "123456";
                String encryptPassword = SecurityUtils.encryptPassword(password);
//                if (bausers.size()==0){
                if (StringUtils.isNull(fxUser)){
                    String userPhoto = "/profile/upload/2024/08/12/default_20240812150859A001.png";
                    //保存用户信息
                    if (!userService.checkUserNameUnique(sysUser)) {
                        return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
                    } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !userService.checkPhoneUnique(sysUser)) {
                        return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
                    }
                    sysUser.setNickName(NameUtil.getName());
                    sysUser.setRemark("微信用户");
                    sysUser.setRoleId(2L);
                    sysUser.setUserName(phoneNumber);
                    sysUser.setPhonenumber(phoneNumber);
                    sysUser.setPassword(encryptPassword);
                    sysUser.setSex("2");
                    sysUser.setAvatar(userPhoto);
                    userService.registerUser(sysUser);
                    sysUser.setUserId(sysUser.getUserId());
                    sysUserRoleMapper.insertUserIdAndSole(sysUser);
                    //保存用户信息
                    FxUser fxUser2 = new FxUser();
                    fxUser2.setOpenId(openid);
                    fxUser2.setPhoneNumber(phoneNumber);
                    fxUser2.setSysUserid(sysUser.getUserId());
                    fxUser2.setUserPassword(encryptPassword);
                    fxUser2.setRoleType(2L);
                    fxUser2.setCreateDate(new Date());
                    fxUser2.setUserPhoto(userPhoto);
                    fxUserService.insertFxUser(fxUser2);
                    fxUser2.setUserName("用户:" + fxUser2.getId());
                    String code = ThreadLocalRandom.current().nextInt(10000, 100000)+""+fxUser2.getId();
                    fxUser2.setUserCode(Convert.toLong(code));
                    fxUserService.updateFxUser(fxUser2);
                }else {
                    sysUser = userService.selectUserById(fxUser.getSysUserid());
                    //更新用户信息
                    //  ZyUser zyUserIsExist= zyUser;
                    //   baUser.setPhoneNumber(phoneNumber);
                    //  baUser.setUserName(phoneNumber);
                    if(StringUtils.isEmpty(fxUser.getOpenId())){
                        fxUser.setOpenId(openid);
                    }
                    // password=baUser.getUserPassword();
                    fxUserService.updateFxUser(fxUser);
                }
                //用户存在
                String token = this.login2(sysUser.getUserName(),password);
                ajax.put(Constants.TOKEN, token);
            }
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("登录失败，请联系管理员！");
        }
    }

    public String getPhoneNumber( WxLoginVo getPhoneVo) throws Exception {

        //获取accessToken
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                + "?access_token=" + accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", getPhoneVo.getPhoneCode());
        String reqJsonStr = JSONObject.toJSONString(jsonObject);
        JSONObject wxJson = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));
        String phone_info = wxJson.getString("phone_info");
        JSONObject phone_info1 = JSONObject.parseObject(phone_info);
        String phoneNumber = null;
        try {
            phoneNumber = phone_info1.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("获取用户手机号失败！");
        }
        return phoneNumber;
    }


    public String login2(String username, String password) {
        // 验证码校验
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);

    }

    private  String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential" +
                "&appid=" + WxV3PayConfig.APP_ID +
                "&secret=" + WxV3PayConfig.secret;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String responseBody = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        return jsonObject.getString("access_token");
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 判断是否可以登录
     * @param loginUser
     */
    public void whether(LoginUser loginUser, Long role) {
        List<SysRole> roles = loginUser.getUser().getRoles();
        Set<Long> roleIds = roles.stream().map(SysRole::getRoleId).collect(Collectors.toSet());
//        Long userId = loginUser.getUserId();

        if (!ObjectUtils.isEmpty(role)) {
            if (!roleIds.contains(role) && !roleIds.contains(1L)) {
                throw new GlobalException("暂未授权，登录失败");
            }
        }
    }
}
